<template>
	<view class="page">
		<view class="nav-bar">
			<view class="nav-content">
				<button class="cancel-btn" @click="handleCancel">取消</button>
				<text class="title-text">发布内容</text>
				<button class="publish-btn" @click="handlePublish">发布</button>
			</view>
		</view>
		<view class="main-content">
			<view class="input-wrapper">
				<input type="text" v-model="title" class="title-input" placeholder="请输入标题"
					placeholder-class="placeholder-style" />
				<textarea v-model="content" class="content-input" placeholder="请输入内容"
					placeholder-class="placeholder-style" />

				<view class="category-selector" @tap="showCategoryPicker">
					<text class="category-text">{{selectedCategory.name || '请选择分类'}}</text>
					<uni-icons type="right" size="14" color="#9CA3AF"></uni-icons>
				</view>
			</view>
			<view class="image-upload-grid">
				<view v-for="(image, index) in images" :key="index" class="image-item">
					<ImgVue :src="image" class="uploaded-image" />
					<view class="delete-btn" @tap="deleteImage(index)">
						<uni-icons type="clear" size="14" color="#FFFFFF"></uni-icons>
					</view>
				</view>
				<view v-if="images.length ===0" class="image-item add-image" @tap="uploadAvatar">
					<uni-icons type="plusempty" size="32" color="#9CA3AF"></uni-icons>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup lang="ts">
	import {
		ref,
		onMounted
	} from 'vue'; // 引入 onMounted 生命周期钩子
	import {
		uploadAvatarFile
	} from '../../../api/user';
	import {
		putArtWork
	} from '../../../api/artwork';
	import {
		getCategoryList
	} from '../../../api/category'; // 引入获取分类的 API
	import ImgVue from '../../../components/Img/Img.vue';

	const title = ref('');
	const content = ref('');
	const images = ref([]);

	const selectedCategory = ref(null);
	const categories = ref([]); // 初始空数组，用于存储分类数据

	// 取消操作
	const handleCancel = () => {
		uni.navigateBack({
			delta: 1,
		});
	};

	// 显示分类选择器
	const showCategoryPicker = () => {
		if (categories.value.length === 0) {
			uni.showToast({
				title: '分类数据加载中，请稍候',
				icon: 'none',
			});
			return;
		}

		uni.showActionSheet({
			itemList: categories.value.map((category) => category.name), // 提取分类名称
			success: (res) => {
				selectedCategory.value = categories.value[res.tapIndex]; // 设置选中的分类对象
			},
		});
	};

	// 获取分类列表
	const fetchCategories = async () => {
		try {
			const response = await getCategoryList(); // 调用分类 API
			if (response.code === 200) {
				categories.value = response.data; // 将返回的分类数据赋值给 categories
			} else {
				uni.showToast({
					title: response.message || '分类加载失败',
					icon: 'none',
				});
			}
		} catch (error) {
			console.error('分类加载失败:', error);
			uni.showToast({
				title: '分类加载失败，请检查网络',
				icon: 'none',
			});
		}
	};

	// 页面加载时获取分类数据
	onMounted(() => {
		fetchCategories(); // 加载分类数据
	});

	// 发布操作
	const handlePublish = async () => {
		if (!title.value) {
			uni.showToast({
				title: '请输入标题',
				icon: 'none',
			});
			return;
		}

		if (!selectedCategory.value) {
			uni.showToast({
				title: '请选择分类',
				icon: 'none',
			});
			return;
		}

		if (images.value.length === 0) {
			uni.showToast({
				title: '请至少上传一张图片',
				icon: 'none',
			});
			return;
		}

		const payload = {
			title: title.value,
			description: content.value,
			imgUrl: images.value[0], // 取第一张图片
			categoryId: selectedCategory.value.id, // 取选中的分类 ID
		};

		console.log('发布内容：', payload);

		try {
			const response = await putArtWork(payload);

			if (response.code === 200) {
				uni.showToast({
					title: '发布成功',
					icon: 'success',
				});
				uni.navigateBack({
					delta: 1,
				});
			} else {
				uni.showToast({
					title: response.message || '发布失败',
					icon: 'none',
				});
			}
		} catch (error) {
			console.error('发布失败:', error);
			uni.showToast({
				title: '发布失败，请检查网络',
				icon: 'none',
			});
		}
	};

	// 删除图片
	const deleteImage = (index: number) => {
		images.value.splice(index, 1);
	};

	// 添加图片
	const addImage = (newImage: string) => {
		if (images.value.length >= 9) {
			uni.showToast({
				title: '最多上传9张图片',
				icon: 'none',
			});
			return;
		}
		images.value.push(newImage);
	};

	// 点击头像上传图片
	const uploadAvatar = () => {
		console.log('运行方法');
		uni.chooseImage({
			count: 1, // 限制只能选择一张图片
			success: async (res) => {
				const filePath = res.tempFilePaths[0];
				try {
					const uploadResponse = await uploadAvatarFile(filePath);
					addImage(uploadResponse.data);
					if (uploadResponse.code === 200) {
						uni.showToast({
							title: '图片上传成功',
							icon: 'success',
						});
					} else {
						uni.showToast({
							title: '图片上传失败，请重试',
							icon: 'none',
						});
					}
				} catch (error) {
					console.error('图片上传失败:', error);
					uni.showToast({
						title: '图片上传失败，请检查网络',
						icon: 'none',
					});
				}
			},
		});
	};
</script>
<style>
	page {
		height: 100%;
	}

	.page {
		background-color: #FFFFFF;
		min-height: 100%;
	}

	.nav-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #FFFFFF;
		border-bottom: 1px solid #E5E7EB;
		z-index: 100;
	}

	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		height: 88rpx;
	}

	.cancel-btn {
		font-size: 14px;
		color: #666666;
		background: none;
		padding: 0;
		margin: 0;
		line-height: 1;
	}

	.title-text {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}

	.publish-btn {
		font-size: 14px;
		color: #1890FF;
		background: none;
		padding: 0;
		margin: 0;
		line-height: 1;
		font-weight: 500;
	}

	.main-content {
		padding: 120rpx 0 32rpx;
	}

	.input-wrapper {
		padding: 0 32rpx;
	}

	.title-input {
		width: 100%;
		height: 80rpx;
		font-size: 16px;
		box-sizing: border-box;
		border-bottom: 1px solid #E5E7EB;
	}

	.content-input {
		width: 100%;
		height: 200rpx;
		font-size: 14px;
		box-sizing: border-box;
		padding: 20rpx 0;
		line-height: 1.5;
	}

	.placeholder-style {
		color: #9CA3AF;
	}

	.image-upload-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 32rpx;
		gap: 16rpx;
	}

	.image-item {
		position: relative;
		width: 216rpx;
		height: 216rpx;
		background-color: #F3F4F6;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.uploaded-image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		right: 8rpx;
		top: 8rpx;
		background-color: rgba(0, 0, 0, 0.5);
		width: 40rpx;
		height: 40rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.add-image {
		border: 2rpx dashed #D1D5DB;
		display: flex;
		align-items: center;
		justify-content: center;
	}


	.category-selector {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		border-bottom: 1px solid #E5E7EB;
	}

	.category-text {
		font-size: 14px;
		color: #333333;
	}
</style>